package com.quick.calcu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quick.calcu.entity.AnswerRecord;
import com.quick.calcu.entity.Student;
import com.quick.calcu.entity.WrongQuestion;
import com.quick.calcu.mapper.WrongQuestionMapper;
import com.quick.calcu.service.AnswerRecordService;
import com.quick.calcu.service.StudentService;
import com.quick.calcu.service.WrongQuestionService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class WrongQuestionServiceImpl extends ServiceImpl<WrongQuestionMapper, WrongQuestion> implements WrongQuestionService {

    @Autowired
    private StudentService studentService;

    @Autowired
    private AnswerRecordService answerRecordService;

    @Override
    public List<WrongQuestion> getByStudentId(Long studentId) {
        LambdaQueryWrapper<WrongQuestion> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(WrongQuestion::getStudentId, studentService.getUserIdByStudentId(studentId));
        return list(wrapper);
    }

    @Override
    public WrongQuestion getWithDetails(Long wrongId) {
        WrongQuestion wrongQuestion = getById(wrongId);
        if (wrongQuestion == null) {
            return null;
        }

        // 关联学生信息
        Student student = studentService.getById(wrongQuestion.getStudentId());
        wrongQuestion.setStudent(student);

        // 关联答题记录信息
        AnswerRecord record = answerRecordService.getById(wrongQuestion.getRecordId());
        wrongQuestion.setRecord(record);

        return wrongQuestion;
    }

    @Override
    public boolean deleteByStudentIdAndTime(Long studentId, LocalDate startTime, LocalDate endTime) {
        LambdaQueryWrapper<WrongQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WrongQuestion::getStudentId, studentId);
        // 添加时间范围条件
        wrapper.between(WrongQuestion::getDate, startTime, endTime);
        return remove(wrapper);
    }
}